<title>Test whether SafeBrowsing check is enforced for WebSocket connections or fetch requests.</title>
<script>
const url = new URL(document.location.href);
const contextType = url.searchParams.get('contextType');
const requestType = url.searchParams.get('requestType');

function getRequestUrl() {
  if (requestType == 'websocket') {
    // Construct the WebSocket URL from the page URL. The server should be
    // configured to accept a WebSocket handshake at this endpoint.
    const wsUrl = new URL('/safe_browsing/malware-ws', url);
    wsUrl.protocol = 'ws';
    return wsUrl;
  }

  return new URL('/safe_browsing/malware.html', url);
}

function workerTest() {
  const worker = new Worker('malware_js_request_worker.js');
  worker.onmessage = e => signalComplete(e.data);
  worker.postMessage(getRequestUrl().toString());
}

function sharedWorkerTest() {
  const worker = new SharedWorker('malware_js_request_worker.js');
  worker.onerror = e => signalComplete('SHARED_WORKER_ERROR');
  const port = worker.port;
  port.onmessage = e => signalComplete(e.data);
  port.postMessage(getRequestUrl().toString());
}

async function serviceWorkerTest() {
  try {
    await navigator.serviceWorker.register('malware_js_request_worker.js');
    const registration = await navigator.serviceWorker.ready;
    const messageChannel = new MessageChannel();
    messageChannel.port1.onmessage = e => signalComplete(e.data);
    registration.active.postMessage(getRequestUrl().toString(),
                                    [messageChannel.port2]);
  } catch (err) {
    signalComplete(`${err}`);
  }
}

function windowTest() {
  const requestUrl = getRequestUrl();
  if (requestUrl.protocol == 'ws:') {
    const ws = new WebSocket(requestUrl.href);
    ws.onerror = () => signalComplete('ERROR');
    ws.onopen = () => signalComplete('NOT BLOCKED');
  } else {
    fetch(requestUrl).then(function(response) {
      signalComplete('NOT BLOCKED');
    }).catch(function() {
      signalComplete('ERROR');
    });
  }
}

function signalComplete(message) {
  // The "not blocked" test looks for this title change to verify that the
  // request has not been blocked.
  document.title = message;
}

switch (contextType) {
  case 'worker':
    workerTest();
    break;

  case 'shared-worker':
    sharedWorkerTest();
    break;

  case 'service-worker':
    serviceWorkerTest();
    break;

  default:
    windowTest();
    break;
}
</script>
